/**
 * ADM 2.0
 * Copyright 2014 Baidu Inc. All rights reserved.
 *
 * @ignore
 * @file 业务表单基类
 * @author maoquan(maoquan@baidu.com)
 */
define(
    function (require) {
        var BaseFormModel = require('ub-ria/mvc/FormModel');
        var GlobalData = require('common/GlobalData');
        var erUtil = require('er/util');
        var util = require('common/util');
        var moment = require('moment');
        var datasource = require('er/datasource');

        /**
         * 数据源配置
         *
         * @type {Object}
         * @override
         */
        var BASE = {
            base: {
                retrieve: function(model) {
                    var data = model.data();
                    var entityName = data.getEntityName();
                    return {
                        entityName: entityName,
                        pascalEntityName: entityName.charAt(0).toUpperCase()
                            + entityName.slice(1)
                    };
                },
                dump: true
            },
            system: function(model) {
                return model.data('global').getSystem();
            },
            user: function(model) {
                var user = model.data('global').getUser();
                if (util.isEmpty(user.detail)) {
                    user.detail = {};
                }
                return user;
            },
            phoneList: function(model) {
                var user = model.get('user');
                if (!util.isEmpty(user.detail) && util.isObject(user.detail.chargePerson)) {
                    var chargePerson = user.detail.chargePerson;
                    return [
                        {
                            text: chargePerson.tel,
                            value: chargePerson.tel
                        },
                        {
                            text: chargePerson.phone,
                            value: chargePerson.phone
                        }
                    ];
                }
                return [];
            },
            timeList: {
                retrieve: function(model) {
                    var timeList = [];
                    var start = moment('2000-01-01 23:30:00');
                    for (var i = 0; i < 48; i++) {
                        var time = start.add(30, 'm').format('hh:mm A');
                        timeList.push(
                            {
                                text: time,
                                value: time
                            }
                        );
                    }
                    return timeList;
                }
            }
            /*,
            cityList: function (model) {
                return model.data('global').getMallList(false);
            },
            mallList: function (model) {
                return model.data('global').getMallList();
            }*/
        };

        var SHOP = {
            shopList: function (model) {
                return [{text: '请选择', value: ''}];
            }
        };

        var ROLE = {
            roleList: function (model) {
                var system = model.get('system');
                return system.roleList;
            }
        };

        function FormModel() {
            BaseFormModel.apply(this, arguments);
            this.addData('global', GlobalData.getInstance());

            this.putDatasource(BASE);
            this.putDatasource(ROLE);
            this.putDatasource(SHOP);
        }

        erUtil.inherits(FormModel, BaseFormModel);

        /**
         * 物料上传控件id列表
         */
        FormModel.prototype.uploaderIds = [];

        /**
         * 对数据源进行预处理
         */
        FormModel.prototype.prepare = function () {
            this.prepareTime(
                {
                    timeField: 'startTime',
                    dateField: 'startDate'
                },
                {
                    timeField: 'endTime',
                    dateField: 'endDate'
                }
            );
            this.set('uploadUrl', '/api/upload/1');
        };

        /**
         * 检验实体有效性
         *
         * @param {Object} entity 提交的实体
         * @return {Object[] | true} 返回`true`表示验证通过，否则返回错误字体
         */
        FormModel.prototype.validateEntity = function (entity) {
            var errorMsg = [];

            // 验证上传控件
            // util.each(
            //     this.uploaderIds,
            //     function (uploaderId){
            //         uploaderId = util.camelize(uploaderId);
            //         if (util.isEmpty(entity[uploaderId])) {
            //             errorMsg.push(
            //                 {
            //                     field: uploaderId,
            //                     message: '请上传文件'
            //                 }
            //             );
            //         }

            //     }
            // );

            return errorMsg;
        };

        /**
         * 判断实体是否有变化
         *
         * @param {Object} entity 新的实体
         * @return {boolean}
         * @overide
         */
        FormModel.prototype.isEntityChanged = function (entity) {
            // 新建模式下的数据修正
            if (this.get('formType') === 'create') {
            }

            // 编辑模式下的数据修正
            if (this.get('formType') === 'update') {
            }
            return false;
        };

        /**
         * 临时保存实体信息
         *
         * @param {Object} entity 实体
         */
        FormModel.prototype.saveEntityState = function (entity) {
            var session = require('common/global/session');
            session.once('editingNews', entity);
        };

        /**
         * 检查实体数据完整性，可在此补充一些视图无法提供的属性
         *
         * @param {Object} entity 实体数据
         * @return {Object} 补充完整的实体数据
         */
        FormModel.prototype.fillEntity = function (entity) {
            var startDate = entity.startDate;
            var startTime = entity.startTime;
            if (startDate && startTime) {
                startDate = moment(startDate).format('YYYY-MM-DD');
                entity.startTime = moment(startDate + ' ' + startTime, 'YYYY-MM-DD hh:mm A').format('YYYY-MM-DD HH:mm');
            }
            var endDate = entity.endDate;
            var endTime = entity.endTime;
            if (endDate && endTime) {
                endDate = moment(endDate).format('YYYY-MM-DD');
                entity.endTime = moment(endDate + ' ' + endTime, 'YYYY-MM-DD hh:mm A').format('YYYY-MM-DD HH:mm');
            }
            entity = util.omit(entity, 'startDate', 'endDate');
            return entity;
        };

        FormModel.prototype.getUrlType = function (pascalType) {
            var url = this.get('url');
            var path = url.getPath();
            var splits = path.split('/');
            var type = splits[1] || 'experience';
            if (pascalType) {
                type = type.charAt(0).toUpperCase() + type.slice(1);
            }
            return type;
        };

        FormModel.prototype.findById = function (id) {
            return BaseFormModel.prototype.findById.call(this, id).then(
                function (result) {
                    return result.data || result;
                }
            );
        };

        FormModel.prototype.prepareObject = function () {
            for (var i = 0; i < arguments.length; i++) {
                var name = arguments[i];
                var obj = this.get(name);
                if (!obj) {
                    this.set(name, {});
                }
            }
        };

        FormModel.prototype.prepareTime = function () {
            for (var i = 0, len = arguments.length; i < len; i++) {
                var field = arguments[i];
                var timeValue = this.get(field.dateField);
                if (timeValue) {
                    timeValue = moment(timeValue, 'YYYY-MM-DD hh:mm');
                }
                else {
                    timeValue = moment();
                }
                this.set(field.dateField, timeValue.toDate());
            }
        };

        return FormModel;
    }
);
